package wpwork.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

/**
 * Dubbo请求过滤器
 */
@Slf4j
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER}, order = 100)
public class MyDubboRequestFilter  implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result;
        //Provider端记录日志
        if(RpcContext.getContext().isProviderSide()){
            long startTime = System.currentTimeMillis();
            result = invoker.invoke(invocation);
            long elapsed = System.currentTimeMillis() - startTime;

            String baselog = "Client[" + CommonConstants.PROVIDER + "],InterfaceName=[" + invocation.getInvoker().getInterface().getSimpleName() + "],MethodName=[" + invocation.getMethodName() + "]";
            if(result.hasException()){
                log.error("DUBBO - 处理异常： {}, Exception = {}", baselog, result.getException());
            }else{
                if(log.isDebugEnabled()){
                    log.debug("DUBBO - 服务响应: {}, Elapsed=[{}ms]", baselog, elapsed);
                }
            }

        }else {
            result = invoker.invoke(invocation);
        }
        return result;
    }

}
